import { provide, ref } from "vue";
import { cloneDeep } from "lodash";

export function useEvent({canvasBtnEvent}) {
  let selectNode = ref(null);
  let controllNode = null;
  let aiShirtCanvas = null;

  provide('activeSelectNode', selectNode)

  const initAIShirtCanvas = (asc) => {
    aiShirtCanvas = asc;
  }


  function touchStart(e) {
    // 获取点击坐标
    const touches = e.touches || [e];
    const touch = touches[0];

    const query = uni.createSelectorQuery();
    query.select('#controllCanvas').boundingClientRect((rect: any) => {
      if (rect) {
        // 转换为相对于canvas的坐标
        const x = touch.clientX - rect.left;
        const y = touch.clientY - rect.top;

        // console.log('点击位置:', x, y)

        // 检测点击的是哪个元素
        const clickedNode = aiShirtCanvas.getNodeAtPosition(x, y);
        // console.log('点击的元素', clickedNode?._type, clickedNode)
        if (clickedNode?._type === 'btn') {
          controllNode = clickedNode;

          if(['scale', 'rotate'].includes(clickedNode.btnType)) {
            controllNode?.touchStart(e);
          }else {
            canvasBtnEvent(clickedNode)
          }
          return;
        }
        controllNode = null;

        if (clickedNode) {
          // 取消之前选中元素的选中状态
          if (selectNode.value && selectNode.value !== clickedNode) {
            selectNode.value.isSelected = false;
          }
          // 设置新选中的元素
          clickedNode.isSelected = true;
          selectNode.value = clickedNode;
          aiShirtCanvas.draw();
        } else {
          updateSelectNode(null)
        }
        // 原有逻辑
        if (selectNode.value) {
          selectNode.value.touchStart(e);
        }
      }
    }).exec();
  }

  function touchMove(e) {
    if (controllNode) {
      controllNode?.controllSapeNode(selectNode.value, e);
    } else {
      selectNode.value?.touchMove(e);
    }
    aiShirtCanvas.draw()
  }

  function touchUp(e) {
    controllNode = null;
    selectNode.value?.touchEnd(e);
    aiShirtCanvas.draw()
  }

  /**
   * 更新选中元素
   * @param node
   */
  const updateSelectNode = (node) => {
    if(selectNode.value) {
      selectNode.value.isSelected = false;
    }
    console.log('更新选中元素', cloneDeep(node))
    node && (node.isSelected = true);
    selectNode.value = node;
    aiShirtCanvas.draw();
  }

  return {
    touchStart,
    touchMove,
    touchUp,
    selectNode,
    updateSelectNode,
    initAIShirtCanvas
  }
}
